package com.ys.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @ClassName ApiHttpUtils
 * @Description TODO
 * @Author alula
 * @Date 2022-08-26 15:08
 */
public class ApiHttpUtils {
    private static final Logger logger = LoggerFactory.getLogger(ApiHttpUtils.class);


    /**
     * sslPOST请求参数
     * @param data
     * @return
     */
    private static NameValuePair[] requestParams(Map<String, String> data) {
        NameValuePair[] nameValueList = new NameValuePair[data.size()];
        Iterator<Map.Entry<String, String>> it = data.entrySet().iterator();
        int i= 0;
        while (it.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
            nameValueList[i] = new NameValuePair(entry.getKey(), entry.getValue());
            i++;
        }
        return nameValueList;
    }

    /**
     * 请求POST数据方法
     * @param url
     * @param params
     * @return
     */
    public static JSONObject sendHttpClientPost(String url, Map<String, String> params){
        String result = "";
        JSONObject jsonObject = null;
        try {
            HttpClient httpClient = new HttpClient();
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(60 * 1000);
            httpClient.getHttpConnectionManager().getParams().setSoTimeout(60 * 1000);
            PostMethod postMethod = new PostMethod(url);
            if (params != null) {
                postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
                postMethod.setRequestBody(requestParams(params));
            }
            postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpClient.executeMethod(postMethod);
            int statusCode = postMethod.getStatusCode();
            result = new String(postMethod.getResponseBody(), "utf-8");
            if (statusCode != 200) {
                Map<String, Object> sesMap = new HashMap<>();
                sesMap.put("error", false);
                sesMap.put("message", JSONObject.parseObject(result).get("message"));
                sesMap.put("code", statusCode);
                jsonObject = JSONObject.parseObject(JSON.toJSONString(sesMap));
                logger.error("调用API接口sendHttpClientPost失败 Exception, url=" + url + ",postData=" + JSON.toJSONString(params) + result, result);
                return jsonObject;
            }
            if (postMethod != null) {
                postMethod.releaseConnection();
            }
            jsonObject = JSONObject.parseObject(result);
        } catch (ConnectException e)
        {
            logger.error("调用API接口sendPost失败 ConnectException, url=" + url + ",postData=" + JSON.toJSONString(params), e);
        }
        catch (SocketTimeoutException e)
        {
            logger.error("调用API接口sendPost失败 SocketTimeoutException, url=" + url + ",postData=" + JSON.toJSONString(params), e);
        }
        catch (IOException e)
        {
            logger.error("调用API接口sendPost失败 IOException, url=" + url + ",postData=" + JSON.toJSONString(params), e);
        }
        catch (Exception ex)
        {
            Map<String,Object> errorMap = new HashMap<>();
            errorMap.put("success", false);
            errorMap.put("message", ex.getMessage());
            jsonObject = JSONObject.parseObject(JSON.toJSONString(errorMap));
            logger.error("调用API接口sendPost失败 Exception, url=" + url + ",postData=" + JSON.toJSONString(params), ex);
        }
        return jsonObject;
    }

    /**
     * 广告api请求get
     * @param url
     * @param params
     * @return
     */
    public static JSONObject sendHttpClientGet(String url, Map<String, String> params){
        String result = "";
        JSONObject jsonObject = null;
        try {
            HttpClient httpClient = new HttpClient();
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(60 * 1000);
            httpClient.getHttpConnectionManager().getParams().setSoTimeout(60 * 1000);
            GetMethod getMethod= new GetMethod(url);
            if (params != null) {
                for (String key : params.keySet()) {
                    getMethod.addRequestHeader(key, params.get(key));
                }
            }
            int i = httpClient.executeMethod(getMethod);
            result = new String(getMethod.getResponseBody(), "utf-8");
            if (getMethod != null) {
                getMethod.releaseConnection();
            }
            Map<String,Object> sesMap = new HashMap<>();
            if (i == 200){
                sesMap.put("success", true);
                sesMap.put("message", 0);
                sesMap.put("data", result);
                jsonObject = JSONObject.parseObject(JSON.toJSONString(sesMap));
            }else {
                sesMap.put("error", false);
                sesMap.put("message", JSONObject.parseObject(result).get("message"));
                sesMap.put("code", i);
                jsonObject = JSONObject.parseObject(JSON.toJSONString(sesMap));
                logger.error("调用API接口asPost失败 Exception, url=" + url + ",postData=" + JSON.toJSONString(params) + result, result);
            }
        } catch (Exception ex) {
            Map<String,Object> errorMap = new HashMap<>();
            errorMap.put("error", false);
            errorMap.put("message", ex.getMessage());
            jsonObject = JSONObject.parseObject(JSON.toJSONString(errorMap));
            logger.error("调用API接口sendGet失败 Exception, url=" + url + ",getData=" + JSON.toJSONString(params), ex);
        }
        return jsonObject;
    }

    /**
     * post请求携带body参数
     * @param serverURL
     * @param params  body参数 application/json
     * @return
     */
    public static String sendPostBody(String serverURL, String params,Map<String, String> paramsHerder) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        InputStream is = null;
        OutputStreamWriter writer = null;
        try{
            StringBuffer sbf = new StringBuffer();
            String strRead = null;
            URL url = new URL(serverURL);
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");//请求post方式
            connection.setDoInput(true);
            connection.setDoOutput(true);
            //header内的的参数在这里set
            if (paramsHerder != null) {
                for (String key : paramsHerder.keySet()) {
                    connection.setRequestProperty(key,  paramsHerder.get(key));
                }
            }
            connection.connect();
            writer = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
            //body参数放这里
            writer.write(params);
            writer.flush();
            is = connection.getInputStream();
            int statusCode = connection.getResponseCode();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            is.close();
            writer.close();
            connection.disconnect();
            String results = sbf.toString();
            return results;
        }catch (IOException e){
            e.printStackTrace();
            return "400";
        }finally {
            try {
                if(connection != null){
                    connection.disconnect();
                }
                if(reader != null){
                    reader.close();
                }
                if(is != null){
                    is.close();
                }
                if(writer != null){
                    writer.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }


}
